<?php

/**
 * campaign actions.
 *
 * @package    25Mails
 * @subpackage campaign
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class campaignActions extends sfActions {

    public function executeIndex(sfWebRequest $request) {
        $this->campaigns = Doctrine::getTable('Campaign')
                        ->createQuery('a')
                        ->execute();
    }

    public function executeShow(sfWebRequest $request) {
        $this->campaign = $this->getRoute()->getObject();
        $this->forward404Unless($this->campaign);
    }

    public function executeNew(sfWebRequest $request) {
        $this->tags = Doctrine_Core::getTable('Tag')->getTagsArray();
        $this->form = new CampaignForm();
    }

    public function executeCreate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->form = new CampaignForm();

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
        $this->forward404Unless($campaign = $this->getRoute()->getObject(), sprintf('Object campaign does not exist (%s).', $request->getParameter('campaign_id')));
        $this->form = new CampaignForm($campaign);
        $this->tags = Doctrine_Core::getTable('Tag')->getTagsArray();
    }

    public function executeEditrecipients(sfWebRequest $request) {
        $this->campaign = $this->getRoute()->getObject();
//        $this->form = new CampaignRecipientsForm($this->campaign);
//the recipients targets of the campaign
        $this->pager = new sfDoctrinePager('Recipient', 25);
        $this->pager->setQuery(Doctrine_Core::getTable('Recipient')->getTargetRecipientsQuery($this->campaign->getRecipientsFilter(), $this->campaign->getTagsFilter()));
        $this->pager->setPage($request->getParameter('page', 1));
        $this->pager->init();
//        try {
////            $this->pager->getResults();
//        }catch (Exception $e) {
//            $this->getUser()->setFlash('error', $e);
//            $this->pager->setQuery($this->campaign->getTargetRecipients(null));
//            $this->pager->setPage($request->getParameter('page', 1));
//            $this->pager->init();
//        }
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($campaign = $this->getRoute()->getObject(), sprintf('Object campaign does not exist (%s).', $request->getParameter('campaign_id')));
        $this->form = new CampaignForm($campaign);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeUpdaterecipients(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));
        $this->campaign = $this->getRoute()->getObject();
        $this->forward404Unless($this->campaign, sprintf('Object campaign does not exist (%s).', $request->getParameter('campaign_id')));
        $this->form = new CampaignRecipientsForm($this->campaign);
        $this->processForm($request, $this->form);
        $this->redirect('campaign/editrecipients');
    }

    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($campaign = $this->getRoute()->getObject(), sprintf('Object campaign does not exist (%s).', $request->getParameter('campaign_id')));
        $campaign->delete();

        $this->redirect('campaign/index');
    }

    protected function processForm(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $campaign = $form->save();

            $this->redirect('campaign/editrecipients?campaign_id=' . $campaign->getCampaignId());
        }
    }

    public function executeShowonline(sfWebRequest $request) {
        $recipientId = $request->getParameter('rid');
        $campaignId = $request->getParameter('cid');
        $recipient = Doctrine_Core::getTable('Recipient')->findOneByRecipientId($recipientId);
        $campaing = Doctrine_Core::getTable('Campaign')->findOneByCampaignId($campaignId);

        $clickBaseUrl = sfConfig::get('app_click_base_url');
        $template = $campaing->getTemplate();
        $this->output = TfStringUtils::replaceLinks(TfStringUtils::replacePlaceHolders($template->getBodyHtml(), $recipient), $recipient, $template, $clickBaseUrl, $campaing->getCampaignId());
        $this->setLayout('nocsslayout');
    }

    public function executeStats(sfWebRequest $request) {
        $this->campaign = $this->getRoute()->getObject();
        switch ($this->campaign->getStatus()) {
            case 'TO_DO':
            case 'ONGOING':
            case 'ERROR':
                $this->recipientCount = Doctrine::getTable('Recipient')->countRecipientsForFilter($this->campaign->getRecipientsFilter());
                $this->sent = Doctrine::getTable('Mail')->countMailsForCampaign($this->campaign->getCampaignId(), 'SENT');
                break;
            case 'DONE':
                $this->recipientCount = Doctrine::getTable('Mail')->countMailsForCampaign($this->campaign->getCampaignId(), 'SENT');
                $this->sent = $this->recipientCount;
                break;
            default:
                break;
        }
        $this->completionRatio = ($this->sent / $this->recipientCount) * 100;
        $this->clicks = Doctrine::getTable('Click')->countClicksForCampaign($this->campaign->getCampaignId());
        $this->clickRatio = ($this->clicks / $this->sent) * 100;
    }


    /**
     * Generates the output for the Open Flash Chart pie chart
     * @param sfWebRequest $request
     * @return <type>
     */
    public function executePie(sfWebRequest $request) {
        $campaign = $this->getRoute()->getObject();
        $stats = $campaign->getTagStats();

        //Creating a stGraph object
        $g = new stGraph();

        //set background color
        $g->bg_colour = '#FFFFFF';
        //Set the transparency, line colour to separate each slice etc.
        $g->pie(80, '#444444', '{font-size: 12px; color: #000000;}');
        //array two arrray one containing data while other contaning labels
        $g->pie_values(array_values($stats), array_keys($stats));
        //Set the colour for each slice. 
        $g->pie_slice_colours($this->randomizeColors(sizeof($stats)));
        //To display value as tool tip
        $g->set_tool_tip('#val#');

        $g->title('', '{font-size:18px; color: #18A6FF}');
        echo $g->render();

        return sfView::NONE;
    }


    /**
     * Generate an array of HTML colors (eg. #ac43f2) with size $numColors
     * @param integer $numColors
     * @return array
     */
    private function randomizeColors($numColors) {
        for ($i=0; $i<$numColors; $i++){
            $colors[] = $this->getRandomColor();
        }
        return $colors;
    }

    /**
     * Generate a color string (eg. #ac43f2)
     * @return string
     */
    private function getRandomColor() {
        mt_srand((double) microtime() * 1000000);
        $c = '';
        while (strlen($c) < 6) {
            $c .= sprintf("%02X", mt_rand(0, 255));
        }
        return $c;
    }

}
